package com.cn.xiaonuo.common.tools;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayTradePayResponse;
import com.cn.xiaonuo.common.constant.AlipayConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class AlipayTools {

	private static Logger logger = LoggerFactory.getLogger(AlipayTools.class);

	/***
	 *  条码支付  商家扫码用户
	 * @param
	 * @return
	 * @throws Exception
	 */
	public JSONObject createAliPayBusScan(String userThirdCode, String out_trade_no, String total_amount, String subject, String store_id, String passback_params) {


		try {
			// 设置请求参数
			AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
					AlipayConstant.APP_ID,
					AlipayConstant.APP_PRIVATE_KEY,
					"json",
					AlipayConstant.CHARSET,
					AlipayConstant.ALIPAY_PUBLIC_KEY,
					AlipayConstant.SIGNTYPE);


			AlipayTradePayRequest request   =   new AlipayTradePayRequest(); //创建API对应的request类
			JSONObject json = new JSONObject();
			json.put("auth_code", userThirdCode); // 即用户在支付宝客户端内出示的付款码，使用一次即失效，需要刷新后再去付款
			json.put("out_trade_no", out_trade_no); // 商户订单号，商户网站订单系统中唯一订单号
			json.put("scene", "bar_code");//条码支付
			json.put("total_amount", total_amount); // 金额
			json.put("subject", subject);// 交易信息
			json.put("store_id", store_id);// 店铺号
			json.put("timeout_express", "120m"); //订单允许的最晚付款时间
			//json.put("passback_params", passback_params); //预留信息
			json.put("body", passback_params); //预留信息
			request.setBizContent(json.toJSONString());

			request.setNotifyUrl(AlipayConstant.notify_url);
			AlipayTradePayResponse response = alipayClient.execute( request );  //通过alipayClient调用API，获得对应的response类
			String result=response.getBody();

			logger.info(result);
			JSONObject resultJson = JSONObject.parseObject(result);
			String  payResponse=resultJson.getString("alipay_trade_pay_response");
			JSONObject payResponseJson = JSONObject.parseObject(payResponse);
			return  payResponseJson;
		} catch (Exception e) {
			e.printStackTrace();

		}
		return null;
	}

}
